package com.sk.weichat.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.ActionBar;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.cjt2325.cameralibrary.util.LogUtil;
import com.hlg.yueliao.wxapi.WXHelper;
import com.sk.weichat.AppConstant;
import com.sk.weichat.MyApplication;
import com.sk.weichat.R;
import com.sk.weichat.bean.LoginAuto;
import com.sk.weichat.bean.LoginRegisterResult;
import com.sk.weichat.db.InternationalizationHelper;
import com.sk.weichat.db.dao.UserDao;
import com.sk.weichat.helper.DialogHelper;
import com.sk.weichat.helper.LoginHelper;
import com.sk.weichat.helper.PrivacySettingHelper;
import com.sk.weichat.sp.UserSp;
import com.sk.weichat.ui.account.DataDownloadActivity;
import com.sk.weichat.ui.account.LoginActivity;
import com.sk.weichat.ui.account.RegisterActivity;
import com.sk.weichat.ui.account.RegisterUserBasicInfoActivity;
import com.sk.weichat.ui.account.SMSLoginActivity;
import com.sk.weichat.ui.base.ActionBackActivity;
import com.sk.weichat.ui.base.ActivityStack;
import com.sk.weichat.ui.base.BaseActivity;
import com.sk.weichat.ui.base.CoreManager;
import com.sk.weichat.util.AppUtils;
import com.sk.weichat.util.Constants;
import com.sk.weichat.util.DeviceInfoUtil;
import com.sk.weichat.util.Md5Util;
import com.sk.weichat.util.PreferenceUtils;
import com.sk.weichat.util.StringUtils;
import com.sk.weichat.util.ToastUtil;
import com.sk.weichat.view.SelectionFrame;
import com.sk.weichat.volley.Result;
import com.xuan.xuanhttplibrary.okhttp.HttpUtils;
import com.xuan.xuanhttplibrary.okhttp.callback.BaseCallback;
import com.xuan.xuanhttplibrary.okhttp.result.ObjectResult;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;

import static com.xuan.xuanhttplibrary.okhttp.result.Result.CODE_NO_PASSWORD;
import static com.xuan.xuanhttplibrary.okhttp.result.Result.CODE_SUCCESS;

/**
 * 进入到此界面的Activity只可能是4中用户状态 STATUS_USER_TOKEN_OVERDUE
 * 本地Token过期 STATUS_USER_NO_UPDATE
 * 数据不完整
 */
// TODO: 统一继承BaseActivity, 要注意这里不需要登录，
public class UserCheckedActivity extends BaseActivity {
    private static final String TAG = "UserCheckedActivity";
    private TextView mTitleTv;
    private TextView mDesTv;
    private TextView cancel;
    private TextView confirm;
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");// HH:mm:ss

    public static void start(Context ctx) {
        // Log.d(TAG, "start() called with: ctx = [" + ctx + "]");
        // Log.w(TAG, "start: 需要重新登录，", new Exception("需要重新登录，"));
        Intent intent = new Intent(ctx, UserCheckedActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // 清空activity栈，
        ctx.startActivity(intent);
    }

    public UserCheckedActivity() {
        noLoginRequired();
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        View view = getWindow().getDecorView();
//        WindowManager.LayoutParams lp = (WindowManager.LayoutParams)view.getLayoutParams();
//        lp.gravity = Gravity.CENTER;
//        lp.width = (dm.widthPixels * 4) / 5;
//        lp.height = (dm.widthPixels * 4) / 5;
//        getWindowManager().updateViewLayout(view,lp);
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        view.setBackgroundResource(R.drawable.fillet_dialog_bg);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_user_checked);

        // Api 11之后，点击外部会使得Activity结束，禁止外部点击结束
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
            setFinishOnTouchOutside(false);
        }
//        getSupportActionBar().hide();
        initView();
    }

    private void initView() {
        mTitleTv = (TextView) findViewById(R.id.title_tv);
        mDesTv = (TextView) findViewById(R.id.des_tv);
        cancel = findViewById(R.id.cancel);
        confirm = findViewById(R.id.confirm);
        // init status

        // 能进入此Activity的只允许三种用户状态
        int status = MyApplication.getInstance().mUserStatus;

        Date date = new Date(System.currentTimeMillis());
        if (status == LoginHelper.STATUS_USER_TOKEN_OVERDUE) {
            mTitleTv.setText(R.string.overdue_title);
            mDesTv.setText(getString(R.string.token_overdue_des, simpleDateFormat.format(date)));

        } else if (status == LoginHelper.STATUS_USER_NO_UPDATE) {
            mTitleTv.setText(R.string.overdue_title);
            mDesTv.setText(R.string.deficiency_data_des);
        } else if (status == LoginHelper.STATUS_USER_TOKEN_CHANGE) {
            mTitleTv.setText(R.string.logout_title);
//            mDesTv.setText(R.string.logout_des);
            mDesTv.setText(getString(R.string.logout_des, simpleDateFormat.format(date), ""));
            getCurrrentLoginInfomation();
        } else {// 其他的状态，一般不会出现，为了容错，加个判断

            loginAgain();
            return;
            // throw new IllegalStateException("用户状态错误");
        }

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                ActivityStack.getInstance().exit();
                loginAgain();
            }
        });

        confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                loginAgain();
                login(UserSp.getInstance(UserCheckedActivity.this).getTelephone(null), UserSp.getInstance(UserCheckedActivity.this).getPassWord(null));
            }
        });
    }

    private void loginAgain() {
        boolean idIsEmpty = TextUtils.isEmpty(UserSp.getInstance(this).getUserId(""));
        boolean telephoneIsEmpty = TextUtils.isEmpty(UserSp.getInstance(this).getTelephone(null));
//        boolean passwordIsEmpty = TextUtils.isEmpty(UserSp.getInstance(this).getPassWord(null));
        Intent intent;
        if (!idIsEmpty && !telephoneIsEmpty) {
//            intent = new Intent(this, SMSLoginActivity.class);
            intent = new Intent(this, LoginActivity.class).putExtra("phoneNum",UserSp.getInstance(this).getTelephone(null));

        } else {
//            intent = new Intent(this, LoginActivity.class);
            intent = new Intent(this, SMSLoginActivity.class);

        }
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
        finish();
        this.sendBroadcast(new Intent(com.sk.weichat.broadcast.OtherBroadcast.FINISH_MAIN));
        overridePendingTransition(R.anim.anim_right_in, R.anim.up_out_anim);

    }

    /**
     * @param自动登录，
     */
    private void login(String phoneNumber, String password) {

        LogUtil.e("aaaaaaa", phoneNumber + "dd" + phoneNumber);
        PreferenceUtils.putInt(this, Constants.AREA_CODE_KEY, 86);

        if (TextUtils.isEmpty(phoneNumber) && TextUtils.isEmpty(password)) {
            Toast.makeText(mContext, getString(R.string.please_input_account_and_password), Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(phoneNumber)) {
            Toast.makeText(mContext, getString(R.string.please_input_account), Toast.LENGTH_SHORT).show();
            return;
        }

        if (TextUtils.isEmpty(password)) {
            Toast.makeText(mContext, InternationalizationHelper.getString("JX_InputPassWord"), Toast.LENGTH_SHORT).show();
            return;
        }

     /*   if (!StringUtils.checkPassword(password)) {
            ToastUtil.showToast(mContext, getString(R.string.password_confirm_password_type));
            return;
        }*/
        // 加密之后的密码
//        final String digestPwd = Md5Util.toMD5(password);
        // 加密后的手机号码
        String digestPhoneNumber = Md5Util.toMD5(phoneNumber);

        DialogHelper.showDefaulteMessageProgressDialog(this);

        Map<String, String> params = new HashMap<>();
        params.put("telephone", digestPhoneNumber);          // 账号登录的时候需要MD5加密，服务器需求
        params.put("password", password);
        params.put("xmppVersion", "1");
        // 附加信息+
        params.put("model", DeviceInfoUtil.getModel());
        params.put("osVersion", DeviceInfoUtil.getOsVersion());
        params.put("serial", DeviceInfoUtil.getDeviceId(mContext));
        // 地址信息
        double latitude = MyApplication.getInstance().getBdLocationHelper().getLatitude();
        double longitude = MyApplication.getInstance().getBdLocationHelper().getLongitude();
        if (latitude != 0)
            params.put("latitude", String.valueOf(latitude));
        if (longitude != 0)
            params.put("longitude", String.valueOf(longitude));

        if (MyApplication.IS_OPEN_CLUSTER) {// 服务端集群需要
            String area = PreferenceUtils.getString(this, AppConstant.EXTRA_CLUSTER_AREA);
            if (!TextUtils.isEmpty(area)) {
                params.put("area", area);
            }
        }

        HttpUtils.get().url(CoreManager.getConfig(this).USER_SWITCH_LOGIN)
                .params(params)
                .build()
                .execute(new BaseCallback<LoginRegisterResult>(LoginRegisterResult.class) {

                    @Override
                    public void onResponse(com.xuan.xuanhttplibrary.okhttp.result.ObjectResult<LoginRegisterResult> result) {
                        DialogHelper.dismissProgressDialog();
                        boolean legal = result != null && result.getResultCode() == CODE_SUCCESS;
                        if (!legal) {
                            String tips;
                            if (result.getResultMsg().equals("账号不存在，请通过验证码登录!")
                                    && result.getResultCode() == 0) {
                                tips = result.getResultMsg();
                            } else if (result.getResultCode() == CODE_NO_PASSWORD) {//未设置密码
                                tips = result.getResultMsg();
                            } else {
                                ToastUtil.showToast(mContext, result.getResultMsg());
                                return;
                            }
                            return;
                        }
                        if (result.getData().getIsRegister() == 1) {
                            boolean success = LoginHelper.setLoginUser(mContext, coreManager, phoneNumber, password, result);
                            if (success) {
                                PreferenceUtils.putBoolean(UserCheckedActivity.this, Constants.LOGIN_CONFLICT, false);// 重置登录冲突记录
                                LoginRegisterResult.Settings settings = result.getData().getSettings();
                                MyApplication.getInstance().initPayPassword(result.getData().getUserId(), result.getData().getPayPassword());
                                PrivacySettingHelper.setPrivacySettings(UserCheckedActivity.this, settings);
                                startActivity(new Intent(mContext, DataDownloadActivity.class));
                                overridePendingTransition(R.anim.anim_right_in, R.anim.up_out_anim);
                                finish();
                            } else { //  登录出错 || 用户资料不全
                                String message = TextUtils.isEmpty(result.getResultMsg()) ? getString(R.string.tip_incomplete_information) : result.getResultMsg();
                                ToastUtil.showToast(mContext, message);
                            }
                        } else {
                            Intent intent = new Intent(getApplicationContext(), RegisterUserBasicInfoActivity.class);
                            intent.putExtra(RegisterActivity.EXTRA_AUTH_CODE, "" + result.getData().getAreaCode());
                            intent.putExtra(RegisterActivity.EXTRA_PHONE_NUMBER, result.getData().getTelephone());
                            intent.putExtra(RegisterActivity.EXTRA_INVITE_CODE, "");
                            intent.putExtra(RegisterActivity.EXTRA_PASSWORD, "");

                            //微信
                            if (result.getData().getWxUser() != null) {
                                if (!TextUtils.isEmpty(result.getData().getWxUser().getNickName())) {
                                    intent.putExtra("nickname", result.getData().getWxUser().getNickName());
                                    intent.putExtra("sex", result.getData().getWxUser().getSex());
                                    intent.putExtra("imgurl", result.getData().getWxUser().getImgurl());
                                    intent.putExtra("thirdToken", "");
                                }
                            }

                            //QQ
                            if (result.getData().getQqUser() != null) {
                                if (!TextUtils.isEmpty(result.getData().getQqUser().getNickName())) {
                                    intent.putExtra("nickname", result.getData().getQqUser().getNickName());
                                    intent.putExtra("sex", result.getData().getQqUser().getSex());
                                    intent.putExtra("imgurl", result.getData().getQqUser().getImgurl());
                                    intent.putExtra("thirdToken", "");
                                }
                            }
                            startActivity(intent);
                            finish();
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        DialogHelper.dismissProgressDialog();
                        ToastUtil.showErrorNet(mContext);
                    }
                });
    }


    /**
     * 获取登录设备信息
     */
    private void getCurrrentLoginInfomation() {

        if(TextUtils.isEmpty(coreManager.getSelf().getUserId())){
            finish();
            return;
        }
        Map<String, String> params = new HashMap<String, String>();
        params.put("access_token", coreManager.getSelfStatus().accessToken);
        params.put("userId", coreManager.getSelf().getUserId());
        params.put("serial", DeviceInfoUtil.getDeviceId(this));

        // 地址信息
        double latitude = MyApplication.getInstance().getBdLocationHelper().getLatitude();
        double longitude = MyApplication.getInstance().getBdLocationHelper().getLongitude();
        if (latitude != 0)
            params.put("latitude", String.valueOf(latitude));
        if (longitude != 0)
            params.put("longitude", String.valueOf(longitude));

        HttpUtils.get().url(coreManager.getConfig().USER_LOGIN_INFO)
                .params(params)
                .build()
                .execute(new BaseCallback<LoginAuto>(LoginAuto.class) {

                    @Override
                    public void onResponse(ObjectResult<LoginAuto> result) {
                        Log.e("lzs", "onResponse" + result.getResultCode());
                        Date date = new Date(System.currentTimeMillis());
                        if (result.getResultCode() == 1||result.getResultCode()==1040327) {//1040327 设备失效
                            mDesTv.setText(getString(R.string.logout_des, simpleDateFormat.format(date), result.getData().getLogin().getModel()));
                        } else {
                            mDesTv.setText(getString(R.string.logout_des, simpleDateFormat.format(date), "其它"));
                        }
                    }

                    @Override
                    public void onError(Call call, Exception e) {
                        Date date = new Date(System.currentTimeMillis());
                        mDesTv.setText(getString(R.string.logout_des, simpleDateFormat.format(date), "其它"));
                        Log.e("lzs", "e:" + e.getMessage());
                    }
                });


    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Log.e("lzs", "onNewIntent");
    }

    @Override
    public void onBackPressed() {
        loginAgain();
    }
}
